<template>
  <div class="district-analysis-table">
    <div v-if="loading" class="loading">
      <el-skeleton :rows="5" animated />
    </div>
    <div v-else>
      <el-table
        :data="districtData"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'avgPrice', order: 'descending' }"
      >
        <el-table-column prop="district" label="区域" sortable />
        <el-table-column prop="avgPrice" label="平均价格(元/㎡)" sortable>
          <template #default="scope">
            <span>{{ formatNumber(scope.row.avgPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="minPrice" label="最低价格(元/㎡)" sortable>
          <template #default="scope">
            <span>{{ formatNumber(scope.row.minPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="maxPrice" label="最高价格(元/㎡)" sortable>
          <template #default="scope">
            <span>{{ formatNumber(scope.row.maxPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalHouses" label="房源数量" sortable />
        <el-table-column prop="avgArea" label="平均面积(㎡)" sortable>
          <template #default="scope">
            <span>{{ scope.row.avgArea.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="showDistrictDetail(scope.row.district)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-dialog
        v-model="dialogVisible"
        :title="`${selectedDistrict}区域详情`"
        width="80%"
      >
        <div v-if="districtDetailLoading" class="loading">
          <el-skeleton :rows="10" animated />
        </div>
        <div v-else-if="districtDetail" class="district-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="区域名称">{{ districtDetail.district }}</el-descriptions-item>
            <el-descriptions-item label="房源数量">{{ districtDetail.totalHouses }}</el-descriptions-item>
            <el-descriptions-item label="平均价格">{{ formatNumber(districtDetail.avgPrice) }} 元/㎡</el-descriptions-item>
            <el-descriptions-item label="最高价格">{{ formatNumber(districtDetail.maxPrice) }} 元/㎡</el-descriptions-item>
            <el-descriptions-item label="最低价格">{{ formatNumber(districtDetail.minPrice) }} 元/㎡</el-descriptions-item>
            <el-descriptions-item label="平均面积">{{ districtDetail.avgArea.toFixed(2) }} ㎡</el-descriptions-item>
          </el-descriptions>
          
          <h3>热门小区</h3>
          <el-table :data="districtDetail.communities" stripe style="width: 100%; margin-top: 20px;">
            <el-table-column prop="name" label="小区名称" />
            <el-table-column prop="avgPrice" label="平均价格(元/㎡)">
              <template #default="scope">
                <span>{{ formatNumber(scope.row.avgPrice) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="totalHouses" label="房源数量" />
          </el-table>
          
          <h3>户型分布</h3>
          <div class="chart-container" ref="layoutChartContainer"></div>
          
          <h3>价格区间分布</h3>
          <div class="chart-container" ref="priceChartContainer"></div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useAnalysisStore } from '@/stores/analysisStore'

const props = defineProps({
  city: {
    type: String,
    required: true
  }
})

const analysisStore = useAnalysisStore()
const loading = ref(false)
const districtData = ref([])
const dialogVisible = ref(false)
const selectedDistrict = ref('')
const districtDetail = ref(null)
const districtDetailLoading = ref(false)

// 图表相关
const layoutChartContainer = ref(null)
const priceChartContainer = ref(null)
let layoutChart = null
let priceChart = null

const fetchDistrictData = async () => {
  if (!props.city) return
  
  loading.value = true
  try {
    const data = await analysisStore.fetchDistrictAnalysis(props.city)
    districtData.value = data
  } catch (error) {
    console.error('获取区域分析数据失败:', error)
  } finally {
    loading.value = false
  }
}

const showDistrictDetail = async (district) => {
  selectedDistrict.value = district
  dialogVisible.value = true
  districtDetailLoading.value = true
  
  try {
    const data = await analysisStore.fetchDistrictDetail(props.city, district)
    districtDetail.value = data
    
    // 等待DOM更新后初始化图表
    nextTick(() => {
      initCharts()
    })
  } catch (error) {
    console.error('获取区域详细数据失败:', error)
  } finally {
    districtDetailLoading.value = false
  }
}

const initCharts = () => {
  // 初始化户型分布图表
  if (layoutChartContainer.value) {
    layoutChart = echarts.init(layoutChartContainer.value)
    
    const layoutOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'horizontal',
        bottom: 10,
        data: districtDetail.value.layoutDistribution.map(item => item.layout)
      },
      series: [
        {
          name: '户型分布',
          type: 'pie',
          radius: ['30%', '60%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          data: districtDetail.value.layoutDistribution.map(item => ({
            name: item.layout,
            value: item.count
          }))
        }
      ]
    }
    
    layoutChart.setOption(layoutOption)
  }
  
  // 初始化价格分布图表
  if (priceChartContainer.value) {
    priceChart = echarts.init(priceChartContainer.value)
    
    const priceOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: districtDetail.value.priceDistribution.map(item => item.range),
        axisLabel: {
          rotate: 45,
          interval: 0
        }
      },
      yAxis: {
        type: 'value',
        name: '房源数量'
      },
      series: [
        {
          name: '房源数量',
          type: 'bar',
          data: districtDetail.value.priceDistribution.map(item => item.count),
          itemStyle: {
            color: '#5470c6'
          },
          emphasis: {
            itemStyle: {
              color: '#3a56b4'
            }
          },
          barWidth: '60%'
        }
      ],
      grid: {
        left: '5%',
        right: '5%',
        bottom: '15%',
        containLabel: true
      }
    }
    
    priceChart.setOption(priceOption)
  }
}

const formatNumber = (num) => {
  return num ? num.toLocaleString() : '0'
}

const handleResize = () => {
  if (layoutChart) {
    layoutChart.resize()
  }
  if (priceChart) {
    priceChart.resize()
  }
}

watch(() => props.city, () => {
  fetchDistrictData()
})

watch(() => dialogVisible.value, (val) => {
  if (!val) {
    // 关闭对话框时销毁图表
    if (layoutChart) {
      layoutChart.dispose()
      layoutChart = null
    }
    if (priceChart) {
      priceChart.dispose()
      priceChart = null
    }
  }
})

onMounted(() => {
  fetchDistrictData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (layoutChart) {
    layoutChart.dispose()
  }
  if (priceChart) {
    priceChart.dispose()
  }
})
</script>

<style scoped>
.district-analysis-table {
  width: 100%;
}

.loading {
  padding: 20px;
}

.district-detail {
  padding: 10px;
}

.chart-container {
  height: 300px;
  margin: 20px 0;
}

h3 {
  margin-top: 30px;
  margin-bottom: 10px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}
</style> 